package cn.xmall.services.cn.xmall.services.impl;

import cn.xmall.models.Order;
import cn.xmall.models.OrderItem;
import cn.xmall.models.OrderShipping;
import cn.xmall.models.User;
import cn.xmall.services.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;

/**
 * Created by MoTaiXian on 2017/7/21.
 */
@Service
public class IntegratedItemOrderServiceImpl implements IntegratedItemOrderService {

    @Autowired
    UserService userService;
    @Autowired
    ItemOrderService itemOrderService;
    @Autowired
    ItemOrderItemService itemOrderItemService;
    @Autowired
    ItemOrderShippingService itemOrderShippingService;

    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public String placeAnOrder(User user, Order order, List<OrderItem> orderItemList, OrderShipping orderShipping) throws Exception {

        //验证当前登陆用户是否为订单的申请用户
        //User user=userService.getLoggedInUserByToken(token);
        Assert.notNull(user,"user is null");
        order.setUserId(user.getId());
        //Assert.state(user.getId()==order.getUserId(),"illegal order user id"+order.getUserId());
        itemOrderService.create(order);

        Assert.notEmpty(orderItemList,"orderItemList is empty");
        String orderID=order.getOrderId();
        for(OrderItem orderItem:orderItemList){
            orderItem.setOrderId(orderID);
        }
        itemOrderItemService.createByList(orderItemList);

        Assert.notNull(orderShipping,"orderShipping is empty");
        orderShipping.setOrderId(orderID);
        itemOrderShippingService.create(orderShipping);

        return orderID;
    }

}
